<?php
/*

 All rights Reserved, Designed By www.youyacao.com
 @Description:会员
 @author:成都市一颗优雅草科技有限公司
 @version 优雅草松鼠聚合直播系统
 需要商业用途或者定制开发等可访问songshu.youyacao.com  联系QQ:2853810243 422108995 23625059584
 正版系统查询系统 zhengbancha.youyacao.com

*/



namespace app\admin\controller;

use \think\Db;
use \think\Request;

class Member extends Base
{
    public function getlist(){
        $user = $this->user;
        $db = Db::name("user")->alias("u")->join("kl_member_info m","u.id=m.user_id","LEFT")
                ->where('u.user_type','member')->field('u.id,username,money,reg_time,last_login_time,end_time,free_times,offers_days,tuijian_count');
        if(input("type") == 1){
            $db = $db->where("end_time",'>=',time());
        }else if(input("type") == 2){
            $db = $db->where("end_time",'<',time());
        }
        $keyword = input("keyword");

        if(strlen($keyword)){
            $db = $db->where("username","like","%".addslashes($keyword)."%");
        }

        $db = $db->order("id","desc");
        if($user['user_type'] == 'admin'){
            $list = $db->paginate(10);
        }else{
            $list = $db->where("parent_id",$user['id'])->paginate(10);
        }
        //echo '<pre>';var_dump($list);die();
        $list->each(function ($item,$key){
            $item['money'] = number_format($item['money'],2);
            $item['reg_time'] = date('Y-m-d H:i:s',$item['reg_time']);
            $item['last_login_time'] = $item['last_login_time'] ? date('Y-m-d H:i:s',$item['last_login_time']) : '从未登陆';
            $item['end_time'] = $item['end_time'] ? date('Y-m-d H:i:s',$item['end_time']).($item['end_time']<time() ? '[已过期]' : '') : '未激活';
            return $item;
        });
        $this->success($list);
    }

    public function daililist(){
        $this->onlyAdmin();

        $user = $this->user;
        $db = Db::name("user")->alias("u")->join("kl_member_info m","u.id=m.user_id","LEFT")
            ->where('u.user_type','daili')->field('u.id,username,money,tuijianma,reg_time,last_login_time,delete_time,tuijian_count');
        if(input("type") == 1){
            $db = $db->where("delete_time",'>',0);
        }
        $keyword = input("keyword");
        if(strlen($keyword)){
            $db = $db->where("username","like","%".addslashes($keyword)."%");
        }

        $db = $db->order("id","desc");
        if($user['user_type'] == 'admin'){
            $list = $db->paginate(10);
        }else{
            $list = $db->paginate(10);
        }
        //echo '<pre>';var_dump($list);die();
        $list->each(function ($item,$key){
            $item['money'] = number_format($item['money'],2);
            $item['delete_time'] = $item['delete_time'] ? "已封号[".date('Y-m-d H:i:s',$item['delete_time'])."]" : '';
            $item['reg_time'] = date('Y-m-d H:i:s',$item['reg_time']);
            $item['last_login_time'] = $item['last_login_time'] ? date('Y-m-d H:i:s',$item['last_login_time']) : '从未登陆';
            return $item;
        });
        $this->success($list);
    }

    public function modifypass(){
        if(!request()->isPost()) $this->error('请求类型有误');

        $uid = intval(input("uid"));
        $password = input("password");
        if(strlen($password)<6) $this->error("密码不能小于6位");
        $db = Db::name("user")->where("id",$uid);
        if($this->user['user_type'] == 'daili') $db = $db->where("parent_id",$this->user['id']);
        $user = $db->find();
        if(!$user) $this->error("未找到你要修改的用户");
        if(Db::name("user")->where("id",$user['id'])->setField("password",md5($password))){
            $this->success(NULL,"修改成功");
        }else{
            $this->error("遇到未知错误，修改失败");
        }
    }

    public function paymoney(){
        if(!request()->isPost()) $this->error('请求类型有误');
        $uid = intval(input("uid"));
        $username = input("username");
        $paymoney = floatval(input("paymoney"));

        if(strlen($username)){
            $user = Db::name("user")->where("username",$username)->find();
        }else{
            $user = Db::name("user")->where("id",$uid)->find();
        }
        if(!$user) $this->error("未找到相应用户");

        if($paymoney<=0 && $this->user['user_type'] != 'admin') $this->error("转款金额不能小于或等于0");
        if($paymoney==0) $this->error("转款金额不能等于0");
        if($this->user['user_type'] == 'daili' && $this->user['money']<$paymoney) $this->error("您的余额不足");


        Db::startTrans();
        try {
            //只创建订单，不真实扣钱
            $data = array();
            $data['user_id'] = $this->user['id'];//订单用户
            $data['payuser_id'] = $user['id'];//收款人用户
            $data['order_no'] = date('YmdHis').rand(1000000,9999999);
            $data['need_money'] = $paymoney;
            $data['type'] = $this->user['user_type'] == 'admin' ? 1 : 2;//0为购买，1为管理员转账，2为代理转账
            $utype = $user['user_type'] == 'daili' ? '代理' : ($user['user_type'] == 'member' ? '会员' : '');
            $data['info'] = $paymoney < 0 ? '给'.$utype.'【'.$user['username'].'】减点' : '转账给'.$utype.'【'.$user['username'].'】';
            $data['create_time'] = time();
            if(Db::name("orders")->insert($data)){
                $orderid = Db::name('orders')->getLastInsID();
                Db::commit();
                $this->success($orderid,"订单创建成功，确认提交？");
            }else{
                Db::rollback();
                $this->error("创建订单失败");
            }
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();//var_dump($e);
            return $this->error('未知错误，订单生成失败');
        }
    }

    public function dopaymoney(){
        $orderid = intval(input("orderid"));
        $order = Db::name("orders")->where("id",$orderid)->where("user_id",$this->user['id'])->find();
        if(!$order) $this->error("订单不存在");
        if($order['need_money']<=0 && $this->user['user_type'] != 'admin') $this->error("转款金额不能小于或等于0");
        if($order['need_money']==0) $this->error("转款金额不能等于0");
        Db::startTrans();
        try {
            //更新转款人资金信息
            if($this->user['user_type'] != 'admin'){//管理员不需要扣出余额
                $user = Db::name("user")->where("id",$this->user['id'])->find();//使用事务锁查询余额
                $balance = $user['money'] - $order['need_money'];
                if($balance<0) $this->error("余额不足，不能完成支付");
                if(Db::name("user")->where("id",$user['id'])->setField("money",$balance)){
                    //创建资金日志
                    $data = array();
                    $data['user_id'] = $user['id'];
                    $data['order_id'] = $order['id'];
                    $data['order_no'] = $order['order_no'];
                    $data['payed_money'] = $order['need_money'];
                    $data['info'] = $order['info'];
                    $data['balance_money'] = $balance;
                    $data['type'] = -1;//-1为扣钱，1为加钱
                    $data['create_time'] = time();
                    Db::name("coin_log")->insert($data);
                }else{
                    Db::rollback();
                    $this->error("未知错误，交易失败");
                }

            }

            //更新收款人资金信息
            $user = Db::name("user")->where("id",$order['payuser_id'])->find();//使用事务锁查询收款人余额
            if(!$user) $this->error("收款人不存在");
            $balance = $user['money'] + $order['need_money'];
            if(Db::name("user")->where("id",$user['id'])->setField("money",$balance)){
                //创建资金日志
                $data = array();
                $data['user_id'] = $user['id'];
                $data['order_id'] = $order['id'];
                $data['order_no'] = $order['order_no'];
                $data['payed_money'] = $order['need_money'];
                $data['info'] = $order['info'];
                $data['balance_money'] = $balance;
                $data['type'] = $order['need_money']>0 ? 1 : -1;//-1为扣钱，1为加钱
                $data['create_time'] = time();
                Db::name("coin_log")->insert($data);
            }else{
                Db::rollback();
                $this->error("未知错误，交易失败");
            }


            //资金变东结束，更新订单信息
            $data = array();
            $data['payed_money'] = $order['need_money'];
            $data['payed_time'] = time();
            if(Db::name("orders")->where("id",$order['id'])->update($data)){
                Db::commit();
                $this->success(NULL,"支付成功");
            }else{
                Db::rollback();
                $this->error("未知错误，交易失败");
            }

        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();var_dump($e);
            return $this->error('未知错误，交易失败');
        }
    }

    public function disable_user(){
        $this->onlyAdmin();

        $uid = intval(input("uid"));
        if(Db::name("user")->where("id",$uid)->setField("delete_time",time())){
            $this->success(NULL,"账号封停成功");
        }else{
            $this->error("未知错误，封停未执行成功");
        }
    }

    public function able_user(){
        $this->onlyAdmin();

        $uid = intval(input("uid"));
        if(Db::name("user")->where("id",$uid)->setField("delete_time",0)){
            $this->success(NULL,"解封账号成功");
        }else{
            $this->error("未知错误，解封账号未执行成功");
        }
    }

    public function modifyyqm(){
        $this->onlyAdmin();

        if(strlen(input("tuijianma"))<5) $this->error("邀请码不能小于5位");

        $uid = intval(input("uid"));
        $user = Db::name("user")->where("id",$uid)->where("user_type","daili")->find();
        if(!$user) $this->error("代理账号不存在");

        if(Db::name("user")->where("id",$uid)->setField("tuijianma",input("tuijianma"))){
            $this->success(NULL,"邀请码修改成功");
        }else{
            $this->error("邀请码已存在，修改失败");
        }
    }
}
